# coding=utf-8
# coding=utf-8
from flask_sqlalchemy import SQLAlchemy
from twisted.enterprise import adbapi
import binascii
import decimal
import datetime
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import json
from gasConfig import cf, db_conn, db_host, db_pass, db_user, db_uri,db_database,gas_group_no

dbpool = adbapi.ConnectionPool(
    db_conn,
    host=db_host,
    user=db_user,
    passwd=db_pass,
    db=db_database,
    charset='utf8',
    cp_reconnect=True)

def _insert_iot_record(trans, record):

    iot_dict = json.loads(record) # 根据字符串书写格式，将字符串自动转换成 字典类型
    try:
        sql = 'insert into iot_history_data (device_id,voltage,humidity,temperature,collect_time)'+\
              ' values(\'%s\',\'%6.2f\',\'%6.2f\',\'%6.2f\',\'%s\')' % (
            iot_dict['id'],  iot_dict['voltage'], iot_dict['humidity'], iot_dict['temperature'], iot_dict['collecttime'])
        #print sql
        result = trans.execute(sql)
        return 'True'
    except:
        return 'False'

def insert_iot_record(record):
    return dbpool.runInteraction(_insert_iot_record, record)


